#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>
#include <functional>

#include "Log.hpp"
#include "Common.hpp"
#include "Inet_Addr.hpp"
#include "ThreadPool.hpp"


const static int g_sockfd = -1;
const static int g_backlog = 8; // 连接队列的大小

using namespace LogModule;

using task_t = std::function<void()>;

class TcpServer
{
private:
    void Service(int sockfd, Inet_Addr addr)
    {
        while (true)
        {
            // 收消息(读消息)
            char buffer[1024];
            ssize_t n = ::read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                LOG(INFO, "read success\n");
                // 处理业务
                std::string message = "[" + addr.AddrStr() + "]";
                message += buffer;
                std::cout << message << std::endl;
                // 响应给用户
                n = ::write(sockfd, message.c_str(), message.size());
                if (n < 0)
                {
                    LOG(WARNING, "write error\n");
                    break;
                }
                LOG(INFO, "write success\n");
            }
            else if (n == 0)
            {
                LOG(INFO, "read the end of file\n");
                break;
            }
            else
            {
                LOG(INFO, "read error\n");
                break;
            }
        }

        ::close(sockfd);
    }

    static void* Execute(void* args)
    {
        pthread_detach(pthread_self());// 将自己给分离了，避免主线程等待，以及出现类似于僵尸的问题
        ThreadData* td = static_cast<ThreadData*>(args);
        td->_self->Service(td->_sockfd, td->_addr);
        delete td;
        return nullptr;
    }

public:
    TcpServer(uint16_t port)
        : _listensocket(g_sockfd), _port(port), _isrunning(false)
    {
    }

    void InitServer()
    {
        // 1、创建监听套接字
        _listensocket = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listensocket < 0)
        {
            LOG(FATAL, "socket create error\n");
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success, sockfd is %d\n", _listensocket);

        // 2、绑定主机的信息
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;         // IPV4
        local.sin_port = htons(_port);      // 设置端口
        local.sin_addr.s_addr = INADDR_ANY; // 任意 ip
        if (::bind(_listensocket, (struct sockaddr *)&local, sizeof(local)))
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(INFO, "bind success\n");
        // 3、设置监听
        int n = ::listen(_listensocket, g_backlog);
        if (n < 0)
        {
            LOG(FATAL, "listen error");
            exit(LISTEN_ERROR);
        }
        LOG(INFO, "listen success");
    }

    // 内部类
    class ThreadData
    {
    public:
        ThreadData(int sockfd, Inet_Addr& addr, TcpServer* self)
            :_sockfd(sockfd),_addr(addr),_self(self)
        {}

    public:
        int _sockfd;
        Inet_Addr _addr;
        TcpServer* _self;
    };


    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 4、获取链接
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(_listensocket, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
            }
            LOG(INFO, "accept success\n");
            // 处理业务
            // version 0 单进程版 --- 不推荐版本
            Inet_Addr addr(peer);
            // Service(sockfd, addr);
            
            // version 1 多进程版 
            // pid_t id = fork();
            // if(id == 0)
            // {
            //     ::close(_listensocket);
            //     // child
            //     if(fork() > 0)
            //         exit(0);
            //     // 此时是孙子进程
            //     Service(sockfd, addr);
            //     exit(0);
            // }
            // // father
            // ::close(sockfd);
            // pid_t n = waitpid(id, nullptr, 0);
            // if(n < 0)
            // {
            //     LOG(FATAL, "wait failed\n");
            // }
            // LOG(INFO, "wait success\n");

            // version 2 多线程版 
            // pthread_t tid;
            // ThreadData* td = new ThreadData(sockfd, addr, this);
            // pthread_create(&tid, nullptr, Execute, td);

            // version 3 版本线程池版本(此处用线程池不太适合)
            task_t t = std::bind(&TcpServer::Service, this, sockfd, addr);
            ThreadPool<task_t>::getInstance()->PushTask(t);
        }
        _isrunning = false;
    }

    ~TcpServer()
    {
        if (_listensocket > g_sockfd)
        {
            ::close(_listensocket);
        }
    }

private:
    int _listensocket; // 监听套接字
    uint16_t _port;    // 端口号
    bool _isrunning;   // 服务端状态
};